package com.leetcode.剑指offer专项突击版;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 覃国强
 * @date 2022-03-01 20:58
 */
public class 剑指OfferII_010_和为k的子数组 {

  static
  class Solution {
    public int subarraySum(int[] nums, int k) {
      if (nums == null || nums.length == 0) {
        return 0;
      }
      int answer = 0;

      // 前缀和记录
      Map<Integer, Integer> preSumMap = new HashMap<>();
      preSumMap.put(0, 1);

      // 前缀和
      int sum = 0;
      for (int num : nums) {
        sum += num;
        int target = sum - k;
        Integer times = preSumMap.getOrDefault(target, 0);
        answer += times;
        preSumMap.compute(sum, (key, oldValue) -> oldValue == null ? 1 : oldValue + 1);
      }

      return answer;
    }
  }

}
